﻿using System;
using System.Collections.Generic;
using System.Data.Objects;
using System.Data.Objects.DataClasses;
using System.Linq;
using System.Reflection;

namespace KamLib
{
    public interface IEntitiesContainer
    {
        ObjectContext Entities { get; set; }
    }

    /// <summary>
    /// игнорировать [свойства] при копировании данных в Entity
    /// </summary>
    public class ReadOnlyAttribute : Attribute { }

    public static class EntityHelper
    {
        public static void CopyFrom<TSource, TEntity>(this TEntity entity, TSource src)
            where TEntity : EntityObject
        {
            ConvertAttribute.Copy(src, entity, (msrc, mdest) =>
            {
                var attr = (EdmScalarPropertyAttribute)Attribute.GetCustomAttribute(mdest, typeof(EdmScalarPropertyAttribute));
                if (attr != null && attr.EntityKeyProperty) return false;
                return Attribute.GetCustomAttribute(msrc, typeof(ReadOnlyAttribute)) == null;
            });
        }

        public static void CopyFrom<TEntity>(this TEntity entity, Dictionary<string, object> src)
            where TEntity : EntityObject
        {
            ConvertAttribute.CopyFrom(src, entity, (msrc, mdest) =>
            {
                var attr = (EdmScalarPropertyAttribute)Attribute.GetCustomAttribute(mdest, typeof(EdmScalarPropertyAttribute));
                return (attr == null || !attr.EntityKeyProperty);
            });
        }


        public static PropertyInfo TableProp<TEntity>(this ObjectContext db)
            where TEntity : EntityObject
        {
            var t = typeof(ObjectSet<TEntity>);
            return db.GetType().GetProperties().First(p => p.PropertyType == t);
        }
        public static ObjectSet<TEntity> Table<TEntity>(this ObjectContext db)
            where TEntity : EntityObject
        {
            return db.TableProp<TEntity>().GetValue(db, null) as ObjectSet<TEntity>;
        }

        public static MemberInfo[] GetKeyFields<TEntity>()
            where TEntity : EntityObject
        {
            return typeof(TEntity).GetProperties().Where(a =>
            {
                var attr = (EdmScalarPropertyAttribute)Attribute.GetCustomAttribute(a, typeof(EdmScalarPropertyAttribute));
                return (attr != null && attr.EntityKeyProperty);
            }).ToArray();
        }
    }
}